package org.dudemonkey.thread.p64;

import java.util.ArrayList;
import java.util.List;

/**
 * 2020-6-18
 * 线程安全
 */
public class ThreadUnsafe01 {
    static final int THREAD_COUNT=2;
    static final int LOOP_NUMBER=200;

    public static void main(String[] args) {

        /**
         * 1.不安全：
         * 临界资源 具备线程不安全的风险，此处ThreadUnsafeClazz类置身于临界资源中。
         *
         * 2.安全：
         * 若将ThreadUnsafeClazz类放到线程中，则类对象所属为线程私有，线程私有的话均为线程安全。
         */
        ThreadUnsafeClazz tu = new ThreadUnsafeClazz();

        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(()->{
                tu.doloop(LOOP_NUMBER);
            }," thread --> "+(i+1)).start();
        }
    }

}

class ThreadUnsafeClazz {
    List<String> list=new ArrayList<>();

    public void doloop(int loopNumber){
        for (int i = 0; i < loopNumber ; i++) {
            m1();
            m2();
        }
    }

    private void m1(){
        list.add("1");
    }
    private void m2(){
        list.remove(0);
    }
}